Skip to content

[Bug Fix] Restore global grad switch when a composite backward node throws - #79923

Closed
omoYang wants to merge 2 commits into
PaddlePaddle:developfrom
omoYang:fix-prim-grad-stop-gradient-restore
Closed

omoYang wants to merge 2 commits into
PaddlePaddle:developfrom
omoYang:fix-prim-grad-stop-gradient-restore

Conversation

@omoYang

@omoYang omoYang commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

PR Category

Execute Infrastructure

PR Types

Bug fixes

Description

背景

走 prim 组合路径的反向节点(MatmulDoubleGradNode、`SiluDoubleGradNode 等)在执行期间必须把全局grad开关关掉,否则反向计算自身又会建图。因为它们的组合实现调用的是可微的前向 API(paddle/fluid/prim/api/composite_backward/composite_double_backward_api.h 中的 matmul、reshape、add)。
这里对全局grad开关的关闭/恢复是在模版中手工实现的,中间没有任何守卫:

bool original_global_grad = egr::Controller::Instance().HasGrad();
if (!create_graph) {
  egr::Controller::Instance().SetHasGrad(create_graph);   // off
}
paddle::prim::matmul_double_grad<paddle::Tensor>(...);     // may throw
if (!create_graph) {
  egr::Controller::Instance().SetHasGrad(original_global_grad);  // not reached
}

一旦组合实现内部抛出异常(形状校验、OOM、NaN 检查等),恢复那一行就被跳过。异常本身能正常传到 Python 层,但g_has_grad梯度开关在该线程剩余的生命周期内一直为 false,除非显示调用set_grad_enabled(True)。
如果grad开关一直被关,此后所有新的前向都静默停止记录计算图:输出带 stop_gradient=True,paddle.grad 找不到可求导路径,loss.backward() 不产生梯度,整个过程没有任何报错或警告。
任何捕获了反向异常后继续运行的代码都会受影响:

try:
    loss.backward()
except Exception:
    handle_or_skip()      # skip a bad batch, retry, fall back
# from here on nothing is recorded, no parameter gets a gradient,
# the loss stops going down, and nothing is reported

这个问题在一个单进程连续执行多个 case 的测试框架中被检测到:某个 case 反向报错之后,同一worker中后续所有 case 的反向都被静默跳过。

原始代码bug复现

import paddle

x = paddle.randn([4, 8])
y = paddle.randn([8, 0])
dout = paddle.randn([4, 3])     # illegal shape, should be [4, 0]
for t in (x, y, dout):
    t.stop_gradient = False

# matmul_grad itself succeeds thanks to the 0-size fast return
dx, _ = paddle._C_ops.matmul_grad(x, y, dout, False, False)

print(paddle.is_grad_enabled())                 # True
try:
    # MatmulDoubleGradNode fails the K dim check inside matmul's InferMeta
    paddle.grad([dx], [x, y, dout], grad_outputs=[paddle.randn(dx.shape)],
                allow_unused=True)
except ValueError:
    pass
print(paddle.is_grad_enabled())                 # False  <-- leaked

a = paddle.randn([2, 2])
a.stop_gradient = False
print((a * 2).stop_gradient)                    # True   <-- no graph any more

paddle.grad(create_graph=False) 和 Tensor.backward() 都会泄漏;create_graph=True 不会,因为该分支根本不调用 SetHasGrad。不走 prim 路径的节点(AddDoubleGradNode、ScaleGradNode)抛出同样的 EnforceNotMet(InvalidArgument) 却不泄漏 —— 这说明决定因素是这对手工配对的置位/恢复,而不是异常类型。

作为对照,PyTorch 在 create_graph=False 下让 C++ 反向节点抛异常后,torch.is_grad_enabled() 保持为 True。

修复

在 paddle/fluid/eager/api/utils/global_utils.h 中新增 RAII 守卫 egr::HasGradGuard,守卫以 create_graph && HasGrad() 构造,完整保持原语义:create_graph 为真时目标值等于当前值,构造和析构都是空操作,与现有行为(该分支不动开关)一致,紧邻已有的 EagerBackwardStateGuard,并用它替换所有的手工关闭/恢复:

  • eager_gen.py:两处组合分支。问题的主体在这里 —— 生成的 nodes.cc 中 original_global_grad 共出现 77 次,覆盖 prim_white_list 的全部 26 个算子(matmul_double_grad、silu_double_grad、tanh_triple_grad、reshape_double_grad、where_double_grad 等)。
  • multiply_node.cc:手写的 multiply_grad / multiply_double_grad(编译时会忽略模版里的写法采纳这里的)
  • 潜在泄漏点py_layer_node.cc、eager_py_layer.cc、eager_utils.cc:PyLayer 前向/反向以及 saved_tensors_hooks 的 pack/unpack hook 中的同样写法。虽然上面的复现用例到不了这些位置,但从源码上看它们是同一种非异常安全的形态,而且那里的 PADDLE_ENFORCE_NOT_NULL 和提前 return Py_None 同样会跳过恢复。

测试

新增 test/legacy_test/test_grad_enabled_restore_on_backward_error.py,断言反向报错后 paddle.is_grad_enabled() 与调用前一致,且一次无关的前向仍然建图;覆盖 paddle.grad(create_graph=False/True)与 Tensor.backward()。
在未修复的构建上实测:3 failed, 1 passed —— 三条泄漏路径失败、create_graph=True 通过,与上述分析完全吻合。修复后:4 passed。
另外重跑并全部通过:

  • test_pylayer_op.py、test_saved_tensors_hooks.py、test_pylayer_clear_dataptr.py(52 passed),覆盖手工修改的 PyLayer 与 hook 代码
  • test_imperative_double_grad.py、test_imperative_triple_grad.py、test_paddle_imperative_double_grad.py(53 passed),覆盖重新生成的组合反向节点
    并确认重新生成的 nodes.cc 中 has_grad_guard 出现 77 次、original_global_grad 为 0 次。

是否引起精度变化

否

…hrows

Composite (prim) backward nodes turn the global grad switch off before
running and turn it back on afterwards. The set/restore pair was written by
hand with no guard in between, so an exception thrown inside the composite
implementation skipped the restore. The calling thread was then left with
grad recording permanently disabled: every later forward silently stopped
building the graph, with no error or warning.

Add an RAII `egr::HasGradGuard` and use it in place of the manual pairs:

- eager_gen.py: both composite branches, which fixes the 77 occurrences in
  the generated nodes.cc, covering all 26 ops in prim_white_list
- multiply_node.cc: the hand-written multiply_grad / multiply_double_grad
- py_layer_node.cc, eager_py_layer.cc, eager_utils.cc: the same pattern in
  PyLayer forward/backward and in the saved_tensors_hooks pack/unpack hooks,
  where PADDLE_ENFORCE_NOT_NULL and early `return Py_None` could also skip
  the restore

Add a regression test asserting paddle.is_grad_enabled() is unchanged after
a failing backward, for paddle.grad and Tensor.backward().
@Paddle-Review-Bot

Paddle-Review-Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Paddle-Bot Review Board (review完成)

序号 位置 优先级 规则来源 状态
1 保存张量钩子异常路径缺少回归测试 P3 仓库规则:Paddle 基础评审规则 ✅

可维护性建议(总分 92 / 100,只给建议,不影响评审结论)

序号 位置 维度 状态
1 梯度守卫调用点重复组合表达式 设计一致性 ✅
2 梯度守卫注释契约过窄 契约一致性 ✅
3 梯度守卫冗余条件判断 AI 生成债务 ✅
各维度得分(仅评本 PR 改动,点击展开)
86.5 API 表面一致性
88 AI 生成债务
3
88 测试策略
88 命名质量
90 底层优雅度
92 中层优雅度
92 契约一致性
2
93 约定偏离
93 跨模块架构
93 高层优雅度
93 逻辑清晰度
93 设计一致性
1
93 未完成迁移
94 错误处理一致性
95 抽象适配度
95 包组织结构
95 初始化耦合
95 类型安全
— 依赖健康度
— 鉴权一致性

Powered by Nyanpasu claude with Opus 5.5 默认推理级别, please check the suggestions carefully.

const Tensor& tensor) {
bool grad_tmp = egr::Controller::Instance().HasGrad();
egr::Controller::Instance().SetHasGrad(false);
egr::HasGradGuard has_grad_guard(false);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3

这里修复的是一条用户可直接触发的泄漏路径:saved_tensors_hooks 的 pack hook 在 Python 中抛异常时,PyObject_Call 返回 NULL,旧代码在 PADDLE_ENFORCE_NOT_NULL(ret, ...) 处抛出而跳过 SetHasGrad(grad_tmp),此后线程内 grad 记录被关闭。新增测试只覆盖了 composite 反向(MatmulDoubleGradNode)路径,hook 这条路径没有回归覆盖。

建议在 test_grad_enabled_restore_on_backward_error.py 补一个用例:在 paddle.autograd.saved_tensors_hooks(pack_hook, unpack_hook) 中让 pack_hook 抛异常,执行 x * x(x.stop_gradient=False)并 assertRaises,之后断言 paddle.is_grad_enabled() 仍为 True 且新前向的 stop_gradient 为 False;unpack hook 抛异常的情况同理可选。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已在 77214f6 中修复:新增 test_saved_tensors_pack_hook_error 与 test_saved_tensors_unpack_hook_error,分别覆盖 pack/unpack hook 抛异常后 grad 开关恢复。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已补,感谢指出 —— 这条路径比我原先判断的更容易触发,实测确认是用户可直接触发的泄漏。

在 test_grad_enabled_restore_on_backward_error.py 中新增两个用例:

  • test_saved_tensors_pack_hook_error:pack hook 抛异常,覆盖 PackHook::operator()
  • test_saved_tensors_unpack_hook_error:unpack hook 在反向期间抛异常,覆盖 UnPackHook::operator()

注意异常类型是 OSError(errors::External),不是 composite 路径的 ValueError,因此把 check_restored 改成接受期望的异常类型。

修复前后对比(同一份测试):未修复构建 5 failed / 1 passed,修复后 6 passed。两条新用例都在未修复构建上失败,确认有回归价值。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已核对:两条新用例分别覆盖 PackHook 与 UnPackHook 的抛异常路径,期望 OSError 与 errors::External 的映射一致(paddle/fluid/pybind/exception.cc:73)。此问题已解决。

// silently stops recording the computation graph.
class HasGradGuard {
public:
explicit HasGradGuard(bool value)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 可维护性建议(设计一致性,不阻塞合入):create_graph && egr::Controller::Instance().HasGrad() 在 eager_gen.py 两处模板、multiply_node.cc 两处和 py_layer_node.cc 中重复出现,其中 && HasGrad() 是承重项:若被“化简”为 HasGradGuard(create_graph),在外层 no_grad 下 create_graph=True 时会把 grad 重新打开。建议在 guard 上提供表达意图的入口(例如 explicit HasGradGuard(bool value) 之外增加 static 工厂或第二个构造参数,如“仅在 !create_graph 时关闭”),由 guard 内部计算 original_ && create_graph,调用点不再重复该组合。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已在 77214f6 中处理:guard 内部计算 original_ && keep_grad,调用点统一传 create_graph,不会在 no_grad 下重新打开记录。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已按建议改,并且采用了比加工厂函数更彻底的做法:把组合算进唯一的构造函数,参数语义从「目标值」改为「是否保留」。

explicit HasGradGuard(bool keep_grad)
    : original_(Controller::Instance().HasGrad()) {
  Controller::Instance().SetHasGrad(original_ && keep_grad);
}

这样 original_ && keep_grad 永远不大于 original_,守卫在结构上就不可能把开关打开。调用点直接写 HasGradGuard(create_graph) 即为正确,你指出的「化简后在 no_grad 下重新打开 grad」从根上不存在了 —— 原来那个容易被误简化的写法,现在成了唯一写法。

所有调用点已去掉 && HasGrad();hook 处的 HasGradGuard(false) 语义不变(original_ && false 恒为 false)。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已核对:构造时写入 original_ && keep_grad,guard 不会把记录重新打开;各调用点传 create_graph 或 false 的行为与原实现一致。此建议已解决。

};

// NOTE(yangyang): Temporarily switch the global grad switch to `value` and
// restore the previous one on scope exit. Composite backward implementations

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 可维护性建议(契约一致性,不阻塞合入):注释把 guard 描述为 composite 反向专用(“Composite backward implementations ... have to turn grad recording off”),但本 PR 也把它用于 PyLayer forward/backward 和 saved_tensors_hooks / NodePostHook,且 create_graph=True 时并不关闭记录。建议注释只描述通用契约:作用域内把全局 grad 开关设为指定值,离开作用域(含异常)时恢复原值;composite 反向的背景放到调用点或去掉。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

同意,已改。注释现在只描述通用契约:作用域内按 keep_grad 设置开关、离开作用域(含异常展开)恢复原值,并显式写出「keep_grad 不会把记录重新打开」这条不变量 —— 这正是上一条里调用点可以直接传 create_graph 的依据。composite 反向的背景已从注释中移除。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已在 77214f6 中处理:注释改为描述通用契约(作用域内按 keep_grad 关闭记录、退出含异常时恢复)。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已核对:注释现在只描述通用契约(按 keep_grad 设置、退出作用域含异常时恢复),并写明 keep_grad 不会重新打开记录,与构造函数 original_ && keep_grad 一致。此建议已解决。

public:
explicit HasGradGuard(bool value)
: original_(Controller::Instance().HasGrad()) {
if (value != original_) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 可维护性建议(AI 生成债务,不阻塞合入):SetHasGrad 只是写一个 thread_local bool(tracer.cc:560),构造与析构中的 if (value != original_) / if (HasGrad() != original_) 判断不改变行为,反而让人误以为调用点的 create_graph && HasGrad() 依赖这个比较。建议与同文件的 EagerBackwardStateGuard 一致,构造时无条件 SetHasGrad(value),析构时无条件 SetHasGrad(original_)。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

同意,已去掉。构造和析构现在都是无条件写入,与同文件的 EagerBackwardStateGuard 保持一致。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已在 77214f6 中处理:构造与析构改为无条件写入,与 EagerBackwardStateGuard 一致。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已核对:构造与析构均为无条件 SetHasGrad,与 EagerBackwardStateGuard 写法一致。此建议已解决。

- HasGradGuard now takes `keep_grad` and sets `original_ && keep_grad`, so it
  can only turn grad recording off, never on. Call sites pass `create_graph`
  directly instead of repeating `create_graph && HasGrad()`, which removes the
  trap where "simplifying" to `HasGradGuard(create_graph)` would re-enable
  recording inside no_grad.
- Drop the no-op comparisons in the constructor and destructor, matching
  EagerBackwardStateGuard.
- Describe the generic contract in the comment instead of the composite
  backward background, since the guard is also used by PyLayer and the
  saved_tensors_hooks.
- Add regression tests for a failing pack hook and a failing unpack hook.
  Both leak on an unfixed build (5 failed, 1 passed) and pass with the fix.
@omoYang

omoYang commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

补充一处评审时可能会注意到的细节,供参考。

在 eager_utils.cc 的几个 hook 里,旧代码的 SetHasGrad(grad_tmp) 位于函数返回语句之前,换成 RAII 守卫后恢复推迟到函数退出,因此函数尾部几行是在 grad 记录关闭的状态下执行的。已逐条确认这些代码不派发任何算子:

  • UnPackHook::operator():PADDLE_ENFORCE_EQ 类型检查、->tensor 的句柄拷贝、Py_XDECREF
  • NodePostHook::operator():CastPyArg2SmallVectorOfVectorOfTensor 仅遍历 list/tuple 做句柄拷贝

恢复发生在调用方拿到返回值之前,所以调用方观察到的开关状态是正确的。

对比 eager_py_layer.cc 和 py_layer_node.cc,那两处用了显式作用域块把守卫限制在 Python 调用这一行:因为调用之后的代码要真的建反向图(如 eager_py_layer.cc 中 require_any_grad && trace_backward 的分支),守卫若延续到函数末尾会破坏 PyLayer 的反向。

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (develop@d47cfae). Learn more about missing BASE report.

Additional details and impacted files
@@             Coverage Diff             @@
##             develop    #79923   +/-   ##
===========================================
  Coverage           ?   100.00%           
===========================================
  Files              ?         3           
  Lines              ?        13           
  Branches           ?         0           
===========================================
  Hits               ?        13           
  Misses             ?         0           
  Partials           ?         0           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@omoYang omoYang closed this Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants